package com.stu.utils;

import java.util.List;

import org.apache.commons.lang.StringUtils;


/**
 * 
 * @author Administrator
 *
 */
public class SqlExpression {
	
	private String name; // a='1'   -->a
	private String operation; // --> =
	private Object value; // -- '1'
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getOperation() {
		return operation;
	}
	public void setOperation(String operation) {
		this.operation = operation;
	}
	public Object getValue() {
		return value;
	}
	public void setValue(String value) {
		this.value = value;
	}
	@Override
	public String toString() {
		return "Expression [name=" + name + ", operation=" + operation
				+ ", value=" + value + "]";
	}
	public SqlExpression() {
		super();
	}
	public SqlExpression(String name, String operation, Object value) {
		super();
		this.name = name;
		this.operation = operation;
		this.value = value;
	}
	
	/**
	 * 
	 * @param expList
	 * @return  WHERE 1=1 ... 
	 */
	public static String getWhere(List<SqlExpression> expList){
		StringBuffer buffer=new StringBuffer(" WHERE 1=1 ");
		SqlExpression sqlExp=null;
		for(int i=0;i<expList.size();i++){
			sqlExp=expList.get(i);
			addWhere(buffer, sqlExp);
		}
		return buffer.toString();
	}
	
	/**
	 * 处理一条 SqlExpression
	 * @param buffer
	 * @param sqlExp
	 */
	private static void addWhere(StringBuffer buffer,SqlExpression sqlExp){
		buffer.append("AND ");
		buffer.append(sqlExp.getName()).append(" ");
		buffer.append(sqlExp.getOperation()).append(" ");
		if(StringUtils.isNotBlank(sqlExp.getValue()+"")){
//			buffer.append(sqlExp.getValue()).append(" ");
			appendValue(buffer, sqlExp.getValue());
		}
	}
	
	/**
	 * 添加 where 值
	 * @param buffer
	 * @param value sqlExpression.getValue()
	 */
	private static void appendValue(StringBuffer buffer,Object value){
		if(value instanceof java.lang.CharSequence){//如果是字符串
			buffer.append("\'").append(value).append("\' ");
		}else{
			if(value instanceof java.lang.Number){
				buffer.append(value).append(" ");
			}
		}
	}
	
	
//	public static void main(String[] args) {
//		List<SqlExpression>list=new ArrayList<SqlExpression>();
//		list.add(new SqlExpression("a", "=", 12));
//		list.add(new SqlExpression("uuid", "like", "%abc%"));
//		System.out.println(getWhere(list));
//	}

}
